﻿using SqlSugar;
using Wechat_PublicNumber.Entity;
using Wechat_PublicNumber.Model.Output;

namespace Wechat_PublicNumber.Repository
{
    public class StockRepository : DataAccess
    {
        /// <summary>
        /// 获取单个股票信息
        /// </summary>
        /// <param name="keyword">Code或者Name</param>
        /// <returns></returns>
        public async Task<Stock> GetStockByKeyword(string keyword) => await WXDb.Queryable<Stock>().Where(s => s.StockCode == keyword || s.StockName == keyword).FirstAsync();

        /// <summary>
        /// 获取用户的股票设置
        /// </summary>
        /// <param name="stockID"></param>
        /// <param name="openID"></param>
        /// <returns></returns>
        public async Task<List<UserStock>> GetUserStockByOpenID(long stockID, string openID) =>
            await WXDb.Queryable<UserStock>().Where(us => us.OpenID == openID && us.StockID == stockID).ToListAsync();

        /// <summary>
        /// 根据ID获取股票设置
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public async Task<UserStock> GetUserStockEntityByID(long ID) =>
            await WXDb.Queryable<UserStock>().Where(us => us.ID==ID).FirstAsync();

        /// <summary>
        /// saveTable
        /// </summary>
        /// <param name="stock"></param>
        /// <param name="userStock"></param>
        /// <returns></returns>
        public async Task SaveUserStock(Stock stock, UserStock userStock)
        {
            var db = WXDb;
            db.Ado.BeginTran();
            try
            {
                var stockID = await db.Insertable(stock).ExecuteReturnBigIdentityAsync();
                userStock.StockID = stockID;
                await db.Insertable(userStock).ExecuteCommandAsync();
                db.Ado.CommitTran();
            }
            catch { db.Ado.RollbackTran(); throw; }
        }

        /// <summary>
        /// saveTable
        /// </summary>
        /// <param name="userStock"></param>
        /// <returns></returns>
        public async Task SaveUserStock(UserStock userStock) => await WXDb.SaveEntityInfo(userStock);

        /// <summary>
        /// 获取股票监听列表
        /// </summary>
        /// <param name="openID"></param>
        /// <param name="KeyWord"></param>
        /// <returns></returns>
        public async Task<List<GetStockList>> GetUserStockList(string openID, string KeyWord)
        {
            RefAsync<int> total = 0;
            var returnData = await WXDb.Queryable<UserStock, Stock>((u, s) => new object[]
              {
                JoinType.Inner,u.StockID==s.ID
              })
             .Where((u, s) => u.OpenID == openID)
             .WhereIF(!string.IsNullOrEmpty(KeyWord), (u, s) => s.StockName.Contains(KeyWord) || s.StockCode.Contains(KeyWord))
             .OrderBy((u, s) => s.StockName, OrderByType.Desc)
             .Select((u, s) => new GetStockList()
             {
                 ID = u.ID,
                 RemindChg = u.RemindChg,
                 RemindPercent = u.RemindPercent,
                 RemindPrice = u.RemindPrice,
                 StockName = s.StockName,
                 StockCode = s.StockCode,
                 BelongStockExchange = s.BelongStockExchange
             })
             .ToPageListAsync(_page.PageIndex, _page.PageSize, total);
            _page.TotalCount = total.Value;

            foreach (var item in returnData)
            {
                item.StockName = $"{item.StockName}({item.BelongStockExchange}{item.StockCode})";
            }

            return returnData;
        }

        /// <summary>
        /// 获取单个
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public async Task<GetStockList> GetUserStockByID(long ID)
        {
            RefAsync<int> total = 0;
            var returnData = await WXDb.Queryable<UserStock, Stock>((u, s) => new object[]
              {
                JoinType.Inner,u.StockID==s.ID
              })
             .Where((u, s) => u.ID == ID)
             .Select((u, s) => new GetStockList()
             {
                 ID = u.ID,
                 RemindChg = u.RemindChg,
                 RemindPercent = u.RemindPercent,
                 RemindPrice = u.RemindPrice,
                 StockName = s.StockName,
                 StockCode = s.StockCode,
                 BelongStockExchange = s.BelongStockExchange
             }).FirstAsync();

            returnData.StockName = $"{returnData.StockName}({returnData.BelongStockExchange}{returnData.StockCode})";

            return returnData;
        }

        /// <summary>
        /// saveStock
        /// </summary>
        /// <param name="stock"></param>
        /// <param name="userStock"></param>
        /// <returns></returns>
        public async Task SaveStock(Stock stock, UserStock userStock)
        {
            var db = WXDb;
            try
            {
                db.Ado.BeginTran();

                var id = await db.SaveEntityInfo(stock);

                userStock.StockID = id;

                await db.SaveEntityInfo(userStock);

                db.Ado.CommitTran();
            }
            catch (Exception)
            {
                db.Ado.RollbackTran();
                throw;
            }
        }

        /// <summary>
        /// DeleteUserStock
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public async Task DeleteUserStock(long ID)
        {
            var userStock = await WXDb.Queryable<UserStock>().FirstAsync(s => s.ID == ID);
            if (userStock != null)
                await WXDb.Deleteable(userStock).ExecuteCommandAsync();
        }
    }
}
